<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use think\App;
use think\facade\Env;
use think\facade\Request;
use think\facade\View;
use think\Response;

class Base extends BaseController
{
    /**
     * @var array
     */
    private array $debug;

    /**
     * @var string|mixed
     */
    public string $app_name;

    /**
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->app_name = config('yijiantianOA.APP_NAME') ?: '';
        View::assign('title', $this->app_name);
        View::assign('website_name', $this->app_name);
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    public function match(array $arr = []): bool
    {
        $request = Request::instance();
        if (!$arr) {
            return false;
        }

        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }

    /**
     * 成功返回
     * @param $data
     * @param string $msg
     * @param int $code
     * @return Response
     */
    public function success($data = [], string $msg = '操作成功', int $code = 1): Response
    {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];

        if (Env::get('APP_DEBUG') && $this->debug) {
            $return['debug'] = $this->debug;
        }

        return json($return);
    }

    /**
     * 错误返回
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return Response
     */
    public function failed(int $code, string $msg = '操作失败', array $data = []): Response
    {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if (Env::get('APP_DEBUG') && $this->debug) {
            $return['debug'] = $this->debug;
        }

        return json($return);
    }

    /**
     * debug参数收集
     * @param $data
     */
    protected function debug($data): void
    {
        if ($data) {
            $this->debug[] = $data;
        }
    }

}